package com.jiangnanxiaoguan.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jiangnanxiaoguan.common.BaseContext;
import com.jiangnanxiaoguan.common.Result;
import com.jiangnanxiaoguan.entity.AddressBook;
import com.jiangnanxiaoguan.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 地址管理 前端控制器
 * </p>
 *
 * @author 不愿透露姓名的狂热者
 * @since 2022-09-11
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 根据用户id查询所有地址。
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> list() {
        // 获取用户的id，用于查询该地址。
        Long currentUserId = BaseContext.getCurrentId();
        log.info("移动端当前用户id：{}", currentUserId);

        // 查询所有地址列表。
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId, currentUserId);
        List<AddressBook> addressBookList = addressBookService.list(addressBookLambdaQueryWrapper);
        return Result.success(addressBookList);
    }

    /**
     * 保存当前用户新增的地址。
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody AddressBook addressBook) {
        log.info(addressBook.toString());
        // 请求携带的json参数中并没有用户id，所有我们取一下，前端直接是取不到用户id的，很正常。
        Long currentUserId = BaseContext.getCurrentId();
        log.info("移动端当前用户id：{}", currentUserId);
        addressBook.setUserId(currentUserId);
        addressBookService.save(addressBook);
        return Result.success("地址保存成功");
    }

    /**
     * 根据地址的id查询，用于修改地址回显。
     *
     * @return
     */
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id) {
        log.info("地址主键：{}", id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 根据地址的id主键修改地址。
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    public Result<String> updateById(@RequestBody AddressBook addressBook) {
        log.info(addressBook.toString());
        addressBookService.updateById(addressBook);
        return Result.success("修改地址成功");
    }

    /**
     * 根据用户id和地址主键id修改为默认地址。
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public Result<String> updateAddressToDefault(@RequestBody AddressBook addressBook) {
        Long id = addressBook.getId();
        log.info("地址主键：{}", id);

        // 将所有默认值修改为0
        // update address_book set is_default = 0 where is_default = 1 and user_id = currentUserId;
        LambdaUpdateWrapper<AddressBook> addressBookLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        Long currentUserId = BaseContext.getCurrentId();
        log.info("移动端当前用户id：{}", currentUserId);
        addressBookLambdaUpdateWrapper.set(AddressBook::getIsDefault, 0)
                .eq(AddressBook::getIsDefault, 1)
                .eq(AddressBook::getUserId, currentUserId);
        addressBookService.update(addressBookLambdaUpdateWrapper);

        // 再设置新的默认地址（方式一）
//        addressBookLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//        addressBookLambdaUpdateWrapper.set(AddressBook::getIsDefault, 1)
//                                      .eq(AddressBook::getUserId, currentUserId)
//                                      .eq(AddressBook::getId, id);
//        addressBookService.update(addressBookLambdaUpdateWrapper);

        // 再设置新的默认地址（方式二）请求参数中
        addressBook.setIsDefault(true);
        addressBookService.updateById(addressBook);

        return Result.success("设置默认地址成功");
    }

    /**
     * 获取默认地址，用于结算页面显示与使用。
     * @return
     */
    @GetMapping("/default")
    public Result<AddressBook> getDefaultAddress() {
        // 用户id(查询条件)
        Long currentUserId = BaseContext.getCurrentId();
        // 查默认地址，即默认值为1(查询条件)的地址。
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId, currentUserId)
                                     .eq(AddressBook::getIsDefault, 1);
        AddressBook defaultAddressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);

        if (defaultAddressBook == null)
            return Result.error("无默认地址");

        return Result.success(defaultAddressBook);
    }

    @DeleteMapping
    public Result<String> delete(Long id) {
        log.info("要删除的地址为 = {}", id);
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getId, id);
        addressBookService.remove(addressBookLambdaQueryWrapper);
        return Result.success("删除地址成功");
    }

}

